package example.controller;

import example.pojo.Supplier;
import example.service.SupplierService;
import example.util.Page;
import org.apache.commons.compress.utils.FileNameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/supplier")
@MultipartConfig(maxFileSize = 1024 * 1024 * 1)
public class SupplierController {
    @Resource
    private SupplierService supplierService;
    private Logger logger = Logger.getLogger(SupplierController.class);

    //供货商信息
    @RequestMapping(value = "/list")
    public String list(Model model, @RequestParam(defaultValue = "1") Integer pageIndex, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String querySupCode = req.getParameter("querySupCode");
        String querySupName = req.getParameter("querySupName");
        Page<Supplier> supplierPage = new Page<Supplier>();
        //设置总数据量
        supplierPage.setTotalPage(supplierService.count(querySupCode, querySupName));
        //设置总页数
        supplierPage.setTotalPageSize();
        //当前页
        supplierPage.setPageIndex(pageIndex);
        //获取当前页数据
        supplierPage.setList(supplierService.select(querySupCode, querySupName, supplierPage.getPageIndex(), supplierPage.getPageSize()));
        //数据回显
        req.setAttribute("querySupCode", querySupCode);
        req.setAttribute("querySupName", querySupName);
        req.setAttribute("supplierList", supplierPage.getList());
        req.setAttribute("totalPageCount", supplierPage.getTotalPageSize());
        req.setAttribute("totalCount", supplierPage.getTotalPage());
        req.setAttribute("currentPageNo", supplierPage.getPageIndex());
        return "supplier/list";
    }

    //前往添加页面
    @GetMapping(value = "/toAdd")
    public String toAdd() {
        return "/supplier/add";
    }

    //添加供货商信息
    @PostMapping(value = "/doAdd")
    public String doAdd(HttpServletRequest req, MultipartFile[] attachs) throws IOException, ServletException {
        //企业营业执照
        String companyLicPic = null;
        //组织机构代码证
        String orgCodePic = null;
        //异常信息
        String errorInfo = null;

        boolean flag = true;
        //文件的存储路径
        String path = req.getSession().getServletContext().getRealPath("statics" + File.separator + "upload");
        logger.info("文件的存储路径：" + path);
        for (int i = 0; i < attachs.length; i++) {
            //拿取单个文件
            MultipartFile attach = attachs[i];
            //文件不为为空时进入
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();  //获取原文件名
                logger.info("原文件名：" + oldFileName);
                //获取原文件后缀
                String prefix = FileNameUtils.getExtension(oldFileName);
                logger.info("原文件后缀:" + prefix);
                //文件大小限制
                int filesize = 500000;
                logger.debug("上传文件大小：" + attach.getSize());
                //上传文件大小不得超过500kb
                if (attach.getSize() > filesize) {
                    req.setAttribute(errorInfo, " * 上传文件大小不得超过500kb");
                    flag = false;
                    //规定上传文件格式
                } else if (prefix.equalsIgnoreCase("jpg")
                        || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pneg")) {
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    logger.debug("新文件名称：" + fileName);
                    //设置路径
                    File targetFile = new File(path);
                    //如果目录不存在则创建
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        //将接收到的文件传递给指定的目录
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        req.setAttribute(errorInfo, "* 上传失败");
                        flag = false;
                    }
                    if (i == 0) {
                        companyLicPic = File.separator + "statics" + File.separator + "upload" + File.separator + fileName;
                    } else if (i == 1) {
                        orgCodePic = File.separator + "statics" + File.separator + "upload" + File.separator + fileName;
                    }
                    logger.debug("idPicPath:" + companyLicPic);
                    logger.debug("workPicPath:" + orgCodePic);
                } else {
                    req.setAttribute(errorInfo, " * 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        //图片成功上传
        if (flag) {
            Supplier supplier = new Supplier();
            //获取参数
            String supCode = req.getParameter("supCode");
            supplier.setSupCode(supCode);
            String supName = req.getParameter("supName");
            supplier.setSupName(supName);
            String supDesc = req.getParameter("supDesc");
            supplier.setSupDesc(supDesc);
            String supContact = req.getParameter("supContact");
            supplier.setSupContact(supContact);
            String supPhone = req.getParameter("supPhone");
            supplier.setSupPhone(supPhone);
            String supAddress = req.getParameter("supAddress");
            supplier.setSupAddress(supAddress);
            String supFax = req.getParameter("supFax");
            supplier.setSupFax(supFax);
            supplier.setCompanyLicPicPath(companyLicPic);
            supplier.setOrgCodePicPath(orgCodePic);

            if (supplierService.add(supplier) > 0) {
                System.out.println("供货商数据添加成功");
                return "redirect:/supplier/list";
            } else {
                System.out.println("供货商数据添加失败");
                return "redirect:/supplier/list";
            }
        }
        throw new RuntimeException("供货商数据添加失败");
    }

    //查看商品详情
    @GetMapping(value = "/view/{supId}")
    public String view(HttpServletRequest req, @PathVariable int supId) {
        logger.info("根据id查询供货商详情：" + supId);
        Supplier supplier = supplierService.view(supId);
        req.setAttribute("supplier", supplier);
        return "supplier/view";
    }

    //前往修改页面
    @GetMapping(value = "/toUpdate/{supId}")
    public String toUpdate(HttpServletRequest req, @PathVariable int supId) {
        logger.info("前往update页面");
        //获取数据后传递到修改页面
        Supplier supplier = supplierService.view(supId);
        req.setAttribute("supplier", supplier);
        return "supplier/update";
    }

    //获取修改后信息，对供货商信息进行修改
    @PostMapping(value = "/doUpdate")
    public String doUpdate(HttpServletRequest req) {
        Supplier supplier = new Supplier();
        //获取参数
        int id = Integer.parseInt(req.getParameter("id"));
        supplier.setId(id);
        String supCode = req.getParameter("supCode");
        String supName = req.getParameter("supName");
        supplier.setSupName(supName);
        String supDesc = req.getParameter("supDesc");
        supplier.setSupDesc(supDesc);
        String supContact = req.getParameter("supContact");
        supplier.setSupContact(supContact);
        String supPhone = req.getParameter("supPhone");
        supplier.setSupPhone(supPhone);
        String supAddress = req.getParameter("supAddress");
        supplier.setSupAddress(supAddress);
        String supFax = req.getParameter("supFax");
        supplier.setSupFax(supFax);

        if (supplierService.upd(supplier) > 0) {
            System.out.println("供货商数据修改成功");
            return "redirect:/supplier/list";
        } else {
            System.out.println("供货商数据修改失败");
        }
        return "supplier/update";
    }
}
